package simi;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class IsImageServlet extends HttpServlet { 

	/**
	 * Need a UID to extend HttpServlet
	 */
	private static final long serialVersionUID = 1L;
	private static final String TEXT_PLAIN = "text/plain";
	private static final String CACHE_CONTROL = "Cache-Control";
	private static final String NO_CACHE = "no-cache";	
	private static final String LAST_MODIFIED = "LAST_MODIFIED";
	private static final String RECENT_IMAGE_FILE = "recentImageFile";
	private static final String NO_IMAGE = "NO_IMAGE";
	private static final String SAME_IMAGE = "SAME_IMAGE";
	private static final String NEW_IMAGE = "NEW_IMAGE";
	private static final String HOME_DIR = "homedir";
	private static FilenameFilter ff = new ImageFileFilter();
					
	public void doGet(HttpServletRequest req, HttpServletResponse res) 
		throws ServletException, IOException { 

		String retVal = NO_IMAGE;
		File lastModifiedImageFile = null;
		
		File dir = new File ((String)req.getSession().getAttribute(HOME_DIR));
			
		// New recurse to get images in sub-directories
		File[] imageFiles = SimiUtils.listFiles(dir, ff, false);
		
		lastModifiedImageFile = SimiUtils.getLastModified(imageFiles);

		if(lastModifiedImageFile != null){							
			retVal = SAME_IMAGE;
			
			// Has it changed since last time?
			// Compare to one in session
			File oneFoundLastTime = (File)
				req.getSession().getAttribute(RECENT_IMAGE_FILE);						
			if(oneFoundLastTime == null || 
			   lastModifiedImageFile.lastModified() > ((Long)req.getSession().getAttribute(LAST_MODIFIED)).longValue()){				 
			   retVal = NEW_IMAGE;			   
			   req.getSession().setAttribute
			   	(RECENT_IMAGE_FILE, lastModifiedImageFile);
			   // Put a Long in session to check the lastModified
			   req.getSession().setAttribute
			   	(LAST_MODIFIED, new Long(lastModifiedImageFile.lastModified()));
			}else{
			
			}
		}	

		res.setContentType(TEXT_PLAIN);
        res.setHeader(CACHE_CONTROL, NO_CACHE);
        PrintWriter pw = res.getWriter();
        pw.write(retVal);
      
        pw.close();			
	} 
}
